package com.clothes.aweiDoExercises.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.clothes.aweiDoExercises.config.AliOssProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Data
@Slf4j
@Component // 声明为 Spring Bean
public class AliOssUtil {

    private final String endpoint;
    private final String accessKeyId;
    private final String accessKeySecret;
    private final String bucketName;

    // 默认配置
    private String rootDir = "uploads";               // 根目录
    private String dateFormatPattern = "yyyy/MM/dd";  // 日期路径格式
    private boolean useHourDir = false;               // 是否使用小时目录

    // 通过构造函数注入配置（Spring 会自动注入 AliOssProperties）
    public AliOssUtil(AliOssProperties aliOssProperties) {
        this.endpoint = aliOssProperties.getEndpoint();
        this.accessKeyId = aliOssProperties.getAccessKeyId();
        this.accessKeySecret = aliOssProperties.getAccessKeySecret();
        this.bucketName = aliOssProperties.getBucketName();
    }

    /**
     * 完全自动上传（按时间编排目录）
     * @param bytes 文件字节数组
     * @param fileExtension 文件扩展名（如 "jpg"、"pdf"）
     * @return 文件URL
     */
    public String upload(byte[] bytes, String fileExtension) {
        // 生成完整路径：根目录/日期路径/小时目录（可选）/UUID.扩展名
        String objectName = buildObjectName(fileExtension);
        return uploadInternal(bytes, objectName);
    }

    /**
     * 完全自动上传（从文件名提取扩展名）
     * @param bytes 文件字节数组
     * @param originalFilename 原始文件名（如 "avatar.jpg"）
     * @return 文件URL
     */
    public String uploadWithFilename(byte[] bytes, String originalFilename) {
        String fileExtension = extractExtension(originalFilename);
        return upload(bytes, fileExtension);
    }

    // 构建完整 objectName
    private String buildObjectName(String fileExtension) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(dateFormatPattern);
        LocalDateTime now = LocalDateTime.now();

        StringBuilder pathBuilder = new StringBuilder();
        pathBuilder.append(rootDir).append("/")
                .append(dateFormatter.format(now));

        if (useHourDir) {
            pathBuilder.append("/").append(now.getHour());
        }

        pathBuilder.append("/").append(UUID.randomUUID().toString());

        if (fileExtension != null && !fileExtension.isEmpty()) {
            pathBuilder.append(".").append(fileExtension);
        }

        return pathBuilder.toString();
    }

    // 从文件名提取扩展名
    private String extractExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    // 内部上传逻辑
    private String uploadInternal(byte[] bytes, String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
            log.info("文件成功上传至OSS: {}", objectName);
        } catch (OSSException | ClientException e) {
            log.error("OSS上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败", e);
        } finally {
            ossClient.shutdown();
        }
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }
}